package com.hspedu.newData.力扣周赛.周赛.第449;

import org.junit.Test;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-05-11 
 * @Version: 1.0
 */

public class Q2等和矩阵分割Ⅰ {
    public boolean canPartitionGrid(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;

        int sum = 0;
        // 统计横向
        int[] horizontal = new int[n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                horizontal[i] += grid[i][j];
                sum += grid[i][j];
            }
        }

        // 统计纵向
        int[] vertical = new int[m];
        for (int j = 0; j < m; j++) {
            for (int i = 0; i < n; i++) {
                vertical[j] += grid[i][j];
            }
        }

        int result = Integer.MAX_VALUE;
        int horizontalCut = 0;
        for (int i = 0; i < n; i++) {
            horizontalCut += horizontal[i];
            result = Math.min(result, Math.abs((sum - horizontalCut) - horizontalCut));
            // 更新result。其中，horizontalCut表示前i行的和，sum - horizontalCut表示剩下的和，作差、取绝对值，得到题目需要的“A和B各自的子区域内的土地总价值之差”。下同。
        }

        int verticalCut = 0;
        for (int j = 0; j < m; j++) {
            verticalCut += vertical[j];
            result = Math.min(result, Math.abs((sum - verticalCut) - verticalCut));
        }

        return result == 0;
    }

    @Test
    public void test() {
        // 测试代码

        int[][] grid = new int[1][2];
        grid[0][0] = 28443;
        grid[0][1] = 33959;
        boolean b = canPartitionGrid(grid);
        System.out.println(b);
    }
}
